package com.software.myopiaparents.utils.sp;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Base64;
import android.util.Log;

import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Map;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;

/**
 * SharedPreferences相关
 */

public class SharedPreferencesUtils {

    public static SharedPreferences sp;
    public static SharedPreferences.Editor editor;

    /**
     * 保存在手机里面的文件名
     */
    public static final String FILE_NAME = "sp_data";
    // 引导页
    public static final String FILE_GUIDE = "sp_guide";
    // 登录的ticket
    public static final String Ticket = "ticket";
    // 引导页
    public static final String Guide = "com.go.xyg.guide";


    /**
     * SPUtils构造函数
     * <p>在Application中初始化</p>
     * @param context 上下文
     * @param spName  spName
     */
    public SharedPreferencesUtils(Context context, String spName) {
        sp = context.getSharedPreferences(spName, Context.MODE_PRIVATE);
        editor = sp.edit();
        editor.apply();
    }

    /**
     * 引导页状态---初始状态 false
     */
    public static void setBooleanGuide(Context mContext, String key, boolean value) {
        SharedPreferences preferences = mContext.getSharedPreferences(FILE_GUIDE, Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean(key, value);
        editor.commit();
    }

    /**
     * 引导页状态---初始状态 false
     */
    public static boolean getBooleanGuide(Context mContext, String key) {
        SharedPreferences sharedPreferences = mContext.getSharedPreferences(FILE_GUIDE, Activity.MODE_PRIVATE);
        boolean b = sharedPreferences.getBoolean(key, false);
        return b;
    }

    /**
     * SP中写入String类型value
     *
     * @param key   键
     * @param value 值
     */
    public static void putString(Context context, String key, String value) {
        sp = context.getSharedPreferences(FILE_NAME, Activity.MODE_PRIVATE);
        editor = sp.edit();
        editor.putString(key, value);
        editor.commit();

    }

    /**
     * SP中读取String
     *
     * @param key 键
     * @return 存在返回对应值，不存在返回默认值{@code null}
     */
    public static String getString(Context context, String key) {
        sp = context.getSharedPreferences(FILE_NAME, Activity.MODE_PRIVATE);
        String string = sp.getString(key, "");
        return string;
    }


    /**
     * SP中写入int类型value
     *
     * @param key   键
     * @param value 值
     */
    public void putInt(String key, int value) {
        editor.putInt(key, value).apply();
    }

    /**
     * SP中读取int
     *
     * @param key 键
     * @return 存在返回对应值，不存在返回默认值-1
     */
    public int getInt(String key) {
        return getInt(key, -1);
    }

    /**
     * SP中读取int
     *
     * @param key          键
     * @param defaultValue 默认值
     * @return 存在返回对应值，不存在返回默认值{@code defaultValue}
     */
    public int getInt(String key, int defaultValue) {
        return sp.getInt(key, defaultValue);
    }

    /**
     * SP中写入long类型value
     *
     * @param key   键
     * @param value 值
     */
    public void putLong(String key, long value) {
        editor.putLong(key, value).apply();
    }

    /**
     * SP中读取long
     *
     * @param key 键
     * @return 存在返回对应值，不存在返回默认值-1
     */
    public long getLong(String key) {
        return getLong(key, -1L);
    }

    /**
     * SP中读取long
     *
     * @param key          键
     * @param defaultValue 默认值
     * @return 存在返回对应值，不存在返回默认值{@code defaultValue}
     */
    public long getLong(String key, long defaultValue) {
        return sp.getLong(key, defaultValue);
    }

    /**
     * SP中写入float类型value
     *
     * @param key   键
     * @param value 值
     */
    public void putFloat(String key, float value) {
        editor.putFloat(key, value).apply();
    }

    /**
     * SP中读取float
     *
     * @param key 键
     * @return 存在返回对应值，不存在返回默认值-1
     */
    public float getFloat(String key) {
        return getFloat(key, -1f);
    }

    /**
     * SP中读取float
     *
     * @param key          键
     * @param defaultValue 默认值
     * @return 存在返回对应值，不存在返回默认值{@code defaultValue}
     */
    public float getFloat(String key, float defaultValue) {
        return sp.getFloat(key, defaultValue);
    }

    /**
     * SP中写入boolean类型value
     *
     * @param key   键
     * @param value 值
     */
    public void putBoolean(String key, boolean value) {
        editor.putBoolean(key, value).apply();
    }

    /**
     * SP中读取boolean
     *
     * @param key 键
     * @return 存在返回对应值，不存在返回默认值{@code false}
     */
    public boolean getBoolean(String key) {
        return getBoolean(key, false);
    }

    /**
     * SP中读取boolean
     *
     * @param key          键
     * @param defaultValue 默认值
     * @return 存在返回对应值，不存在返回默认值{@code defaultValue}
     */
    public boolean getBoolean(String key, boolean defaultValue) {
        return sp.getBoolean(key, defaultValue);
    }

    /**
     * SP中写入boolean类型value
     *
     * @param mContext
     * @param key
     * @param value
     */
    public static void setBooleanData(Context mContext, String key, boolean value) {
        SharedPreferences preferences = mContext.getSharedPreferences(FILE_NAME, Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean(key, value);
        editor.commit();
    }

    /**
     * SP中读取boolean
     *
     * @param mContext
     * @param key
     * @return
     */
    public static boolean getBooleanData(Context mContext, String key) {
        SharedPreferences sharedPreferences = mContext.getSharedPreferences(FILE_NAME, Activity.MODE_PRIVATE);
        boolean b = sharedPreferences.getBoolean(key, false);
        return b;
    }

    /**
     * SP中获取所有键值对
     *
     * @return Map对象
     */
    public Map<String, ?> getAll() {
        return sp.getAll();
    }

    /**
     * SP中移除该key
     *
     * @param key 键
     */
    public void remove(String key) {
        editor.remove(key).apply();
    }

    /**
     * SP中是否存在该key
     *
     * @param key 键
     * @return {@code true}: 存在<br>{@code false}: 不存在
     */
    public boolean contains(String key) {
        return sp.contains(key);
    }

    /**
     * SP中清除所有数据
     */
    public static void clear(Context context) {
        Log.e("sp","SP中清除所有数据");
        sp = context.getSharedPreferences(FILE_NAME, Activity.MODE_PRIVATE);
        editor = sp.edit();
        editor.clear();
        editor.commit();
    }


    /**
     * ============================以下是加密方法=============================
     **/
    private static String getEncryptKey(String data) {
        String r = null;
        try {
            String t = md5Encrypt(data);
            t.substring(0, t.length() / 2);
            r = md5Encrypt(t);
            return r;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private static byte[] md5(String msg) throws Exception {
        return md5(msg.getBytes());
    }

    private static byte[] md5(byte[] bytes) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(bytes);
        return md.digest();
    }

    private static String md5Encrypt(String msg) throws Exception {
        return base64Encode(md5(msg));
    }

    private static String base64Encode(byte[] bytes) {
        return Base64.encodeToString(bytes, Base64.DEFAULT);
    }

    private static byte[] base64Decode(String base64Code) {
        return Base64.decode(base64Code, Base64.DEFAULT);
    }

    private static String aesEncrypt(String content, String encryptKey) throws Exception {
        return base64Encode(aesEncryptToBytes(content, encryptKey));
    }

    private static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        // ------------------------------------------//
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
        sr.setSeed(encryptKey.getBytes());
        // ------------------------------------------//
        kgen.init(128, sr/* new SecureRandom(encryptKey.getBytes()) */);

        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));
        return cipher.doFinal(content.getBytes("utf-8"));
    }

    public static String aesDecrypt(String encryptStr, String decryptKey) throws Exception {
        return aesDecryptByBytes(base64Decode(encryptStr), decryptKey);
    }

    public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        // ------------------------------------------//
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
        sr.setSeed(decryptKey.getBytes());
        // ------------------------------------------//
        kgen.init(128, sr/* new SecureRandom(decryptKey.getBytes()) */);

        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));
        byte[] decryptBytes = cipher.doFinal(encryptBytes);

        return new String(decryptBytes);
    }
    /**=========================END===============================**/
}
